const express = require('express');
const { v4: uuidv4 } = require('uuid');
const router = express.Router();

// 计算餐厅权重
function calculateWeight(frequencyRule) {
  switch (frequencyRule) {
    case 'daily': return 3;
    case 'weekly': return 2;
    case 'monthly': return 1;
    default: return 1;
  }
}

// 加权随机选择
function weightedRandomSelect(restaurants) {
  const totalWeight = restaurants.reduce((sum, restaurant) => {
    return sum + calculateWeight(restaurant.frequency_rule);
  }, 0);
  
  let random = Math.random() * totalWeight;
  
  for (const restaurant of restaurants) {
    random -= calculateWeight(restaurant.frequency_rule);
    if (random <= 0) {
      return restaurant;
    }
  }
  
  return restaurants[restaurants.length - 1];
}

// 获取符合条件的餐厅
async function getEligibleRestaurants(supabase) {
  try {
    // 获取所有餐厅
    const { data: restaurants, error: restaurantError } = await supabase
      .from('restaurants')
      .select('*');
    
    if (restaurantError) throw restaurantError;
    
    // 获取当前有效的标记
    const now = new Date().toISOString();
    const { data: marks, error: markError } = await supabase
      .from('restaurant_marks')
      .select('restaurant_id')
      .gt('expires_at', now);
    
    if (markError) throw markError;
    
    // 过滤掉被标记的餐厅
    const markedRestaurantIds = new Set(marks.map(mark => mark.restaurant_id));
    const eligibleRestaurants = restaurants.filter(restaurant => 
      !markedRestaurantIds.has(restaurant.id)
    );
    
    return eligibleRestaurants;
  } catch (error) {
    console.error('获取符合条件的餐厅失败:', error);
    throw error;
  }
}

// 开始抽签
router.post('/start', async (req, res) => {
  try {
    const eligibleRestaurants = await getEligibleRestaurants(req.supabase);
    
    if (eligibleRestaurants.length === 0) {
      return res.status(400).json({
        success: false,
        data: null,
        message: '没有符合条件的餐厅可以抽签',
        error: {
          code: 400,
          type: 'NoEligibleRestaurants',
          timestamp: new Date().toISOString(),
          path: req.path
        }
      });
    }
    
    const selectedRestaurant = weightedRandomSelect(eligibleRestaurants);
    
    // 记录抽签历史
    const drawHistory = {
      id: uuidv4(),
      restaurant_id: selectedRestaurant.id,
      restaurant_name: selectedRestaurant.name,
      restaurant_category: selectedRestaurant.category,
      draw_time: new Date().toISOString(),
      created_at: new Date().toISOString()
    };
    
    const { data, error } = await req.supabase
      .from('draw_history')
      .insert([drawHistory])
      .select()
      .single();
    
    if (error) throw error;
    
    res.json({
      success: true,
      data: {
        restaurant: selectedRestaurant,
        drawHistory: data
      },
      message: '抽签成功'
    });
  } catch (error) {
    console.error('抽签失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '抽签失败',
      error: {
        code: 500,
        type: 'DatabaseError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

// 重新抽签
router.post('/restart', async (req, res) => {
  try {
    const eligibleRestaurants = await getEligibleRestaurants(req.supabase);
    
    if (eligibleRestaurants.length === 0) {
      return res.status(400).json({
        success: false,
        data: null,
        message: '没有符合条件的餐厅可以抽签',
        error: {
          code: 400,
          type: 'NoEligibleRestaurants',
          timestamp: new Date().toISOString(),
          path: req.path
        }
      });
    }
    
    const selectedRestaurant = weightedRandomSelect(eligibleRestaurants);
    
    // 记录抽签历史
    const drawHistory = {
      id: uuidv4(),
      restaurant_id: selectedRestaurant.id,
      restaurant_name: selectedRestaurant.name,
      restaurant_category: selectedRestaurant.category,
      draw_time: new Date().toISOString(),
      created_at: new Date().toISOString()
    };
    
    const { data, error } = await req.supabase
      .from('draw_history')
      .insert([drawHistory])
      .select()
      .single();
    
    if (error) throw error;
    
    res.json({
      success: true,
      data: {
        restaurant: selectedRestaurant,
        drawHistory: data
      },
      message: '重新抽签成功'
    });
  } catch (error) {
    console.error('重新抽签失败:', error);
    res.status(500).json({
      success: false,
      data: null,
      message: '重新抽签失败',
      error: {
        code: 500,
        type: 'InternalServerError',
        timestamp: new Date().toISOString(),
        path: req.path
      }
    });
  }
});

module.exports = router;